package com.burgeon.backend.service.Impl;


import com.alibaba.fastjson.JSONArray;
import com.burgeon.backend.Rest.Template.Recharge.FindRechargeData;
import com.burgeon.backend.Rest.Template.Reviews.FindRetailData;
import com.burgeon.backend.Rest.Template.Reviews.FindRetailDataZT;
import com.burgeon.backend.Rest.User.GetVipDataByRunner;
import com.burgeon.backend.Rest.membership.GetMembershipData;
import com.burgeon.backend.SHOPBACKEND.service.ex.DataNotFoundException;
import com.burgeon.backend.entity.*;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.RunnerMapper;
import com.burgeon.backend.mappers.UserMapper;
import com.burgeon.backend.service.MessageTemplateService;
import com.burgeon.backend.service.RunnerService;
import com.burgeon.backend.service.WechatService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class RunnerServiceImpl implements RunnerService {

    private final static Log logger = LogFactory.getLog(RunnerService.class);

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private RunnerMapper runnerMapper;
    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WechatService wechatService;

    /**
     * 会员升降级
     */
    @Override
    public void SendMembershipPromotionAndDemotion() {
        //todo 写死了
        Info info = accountMapper.GetAccData("lfwd");

        GetMembershipData getMembershipData = new GetMembershipData(info.getUrl(), info.getAccount(), info.getPassword());

        ArrayList<Membership> data = getMembershipData.getData();
        for ( Membership membership :data){
            messageTemplateService.vipUpgrade(membership.getOpenid(),membership.getCode(),membership.getTime(),
                    membership.getOldType(),membership.getNewType(),"lfwd"
                    );
        }



    }

    /**
     * 同步会员信息
     */
    @Override
    public void synchronizationVipData() {
        List<Info> accList = accountMapper.getShopAccountAll();

        for (Info info : accList) {
            if (!"lfwd".equals(info.getToken())) {
                continue;
            }
            GetVipDataByRunner getVipDataByRunner = new GetVipDataByRunner(info.getUrl(), info.getAccount(), info.getPassword());
            ArrayList<User> data = getVipDataByRunner.getData();
            for (User user : data){
                //修改
                try {
                    userMapper.synUserData(user.getPhone(),info.getToken(),
                            user.getIsEmp(),user.getType(),user.getDiscount(),
                            user.getIsPlus());
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
            }

        }

    }

    @Override
    public void SendConsumptionTemplate() {
        ArrayList<TemplateSwitch> accs = runnerMapper.GetConsumptionTemplateAccount();//获取消费模板是Y的switch信息
        for (TemplateSwitch templateSwitch : accs) {
            Info info = accountMapper.GetAccData(templateSwitch.getAccount());
            FindRetailData findRetailData = new FindRetailData(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                ArrayList<RetailData> retailData = findRetailData.getData(templateSwitch.getValue3());

                for (RetailData retail : retailData) {
                    //发送模板
                    messageTemplateService.SendMessageForConsumption(templateSwitch.getAccount(), retail.getOpenid(), retail.getCode(), retail.getPhone(), retail.getDate());
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
                logger.error("定时任务:" + Arrays.toString(e.getStackTrace()) + e.getMessage());
            }
        }
    }

    @Override
    public void SendRechargeTemplate() {
        ArrayList<TemplateSwitch> accs = runnerMapper.GetRechargeTemplateAccount();//获取充值模板是Y的switch信息
        for (TemplateSwitch templateSwitch : accs) {
            Info info = accountMapper.GetAccData(templateSwitch.getAccount());
            FindRechargeData findRechargeData = new FindRechargeData(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                ArrayList<RechargeData> retailData = findRechargeData.getData();

                for (RechargeData recharge : retailData) {
                    //发送模板

                    messageTemplateService.SendMessageForRecharge(templateSwitch.getAccount(), recharge);
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
                logger.error("定时任务:" + Arrays.toString(e.getStackTrace()) + e.getMessage());
            }
        }
    }

    @Override
    public void SendExpenditureTemplate() {

        ArrayList<TemplateSwitch> accs = runnerMapper.GetExpenditureTemplateAccount();//获取消费模板是Y的switch信息

        for (TemplateSwitch templateSwitch : accs) {

            Info info = accountMapper.GetAccData(templateSwitch.getAccount());
            FindRetailData findRetailData = new FindRetailData(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                ArrayList<RetailData> retailData = findRetailData.getData("0");

                for (RetailData retail : retailData) {

                    //发送模板
                    messageTemplateService.SendMessageForExpenditure(templateSwitch.getAccount(), retail);
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
                logger.error("定时任务:" + Arrays.toString(e.getStackTrace()) + e.getMessage());
            }
        }
    }

    @Override
    public void SynchronousReturnProgress() {

    }

    @Override
    public void SendExtractMessageTemplate(String token) {
        Info info = accountMapper.GetAccData(token);

        FindRetailDataZT findRetailDataZT = new FindRetailDataZT(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            ArrayList<RetailData> retailData = findRetailDataZT.getData();
            String accessToken = wechatService.GetAccesTokenByAccount(token);

            for (RetailData recharge : retailData) {
                com.alibaba.fastjson.JSONObject json = getUserInfo(accessToken,recharge.getOpenid(),token);
                String subscribe = json.getString("subscribe");
                System.err.println("subscribe==="+subscribe);
                if(!"0".equals(subscribe)){
                    messageTemplateService.SendExtractMessageTemplate(recharge.getOpenid(),recharge.getGoodsName(),recharge.getSinceDate(),
                            recharge.getXsno(),recharge.getSelfRaiNo(),recharge.getStore(),recharge.getAddress(),token);
                }

            }


        }catch (Exception e) {
            System.err.println(e.getMessage());
            logger.error("定时任务:" + Arrays.toString(e.getStackTrace()) + e.getMessage());
        }
    }

    private com.alibaba.fastjson.JSONObject getUserInfo(String accessToken, String openId, String token) throws DataNotFoundException {

        // 上传文件请求路径
        String action = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="
                + accessToken+"&openid="+openId;
        System.err.println("j呼吸道咖啡机"+openId);
        // 拼接获取用户信息接口的请求地址
//        String requestUrl = ProjectConst.GET_WEIXIN_USER_URL.replace("ACCESS_TOKEN", accessToken).replace(
//                "OPENID", openId);
        // 获取用户信息(返回的是Json格式内容)
        //封装获取到的用户信息

        try {
            URL urlGet = new URL(action);
            HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String result = new String(jsonBytes, "UTF-8");
            System.err.println("结果"+result);
            com.alibaba.fastjson.JSONObject jsonObject = JSONArray.parseObject(result);

            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("失败");
            return null;
        }

    }

    private Info GetInfo(String account) {
        return accountMapper.GetAccData(account);
    }


}
